<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['group','level'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }

        // 获取用户组列表（使用与edit相同的生成方式）
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), 1, ['class' => 'form-control selectpicker']));

        // 获取用户等级列表
        $levelList = \app\admin\model\user\UserLevel::where('status', '1')
            ->order('weigh DESC, id ASC')
            ->select();
        $this->view->assign("levelList", $levelList);

        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 获取用户等级列表
        $levelList = \app\admin\model\user\UserLevel::where('status', '1')
            ->order('weigh DESC, id ASC')
            ->select();
        $this->view->assign("levelList", $levelList);
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            Db::startTrans();
            try {
                $totalAmount = request()->post("amount");
                if($totalAmount <= 0){
                    $this->error('充值金额不正确');
                }
                // 扣除用户余额
                $newBalance = bcadd($row->money, $totalAmount, 2);
                $updateResult = \think\Db::name('user')
                    ->where('id', $ids)
                    ->update([
                        'money' => $newBalance,
                        'updatetime' => time()
                    ]);

                if ($updateResult === false) {
                    $this->error('修改用户余额失败');
                }

                // 获取管理员信息和IP地址
                $adminId = session('admin.id') ?: 0;
                $adminName = session('admin.nickname') ?: '系统';
                $ip = request()->ip();

                // 记录用户资金流水
                $moneyLogData = [
                    'user_id' => $ids,
                    'money' => -$totalAmount,
                    'before' => $row->money,
                    'after' => $newBalance,
                    'memo' => sprintf(
                        '管理员操作：%s(%s) %s了金额 %s，从 %s 变更为 %s | IP：%s',
                        $adminName,
                        $adminId,
                        '充值',
                        abs($totalAmount),
                        $row->money,
                        $newBalance,
                        $ip
                    ),
                    'createtime' => time()
                ];

                $moneyLogResult = \think\Db::name('user_money_log')->insert($moneyLogData);
                if (!$moneyLogResult) {
                    $this->error('记录资金流水失败');
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success("充值请求成功", null, ['amount'=>$totalAmount,'newBalance' => $newBalance]);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

}
